<?php


namespace App\Helpers;


use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class Bing
{
    var $fileTypes = [
        'UHD',         // 超过1080p的分辨率，统一用这个格式
        // '1920x1200',
        '1920x1080',
        '1366x768',
        '1280x768',
        '1024x768',
        '800x600',
        '800x480',
        '768x1280',
        '720x1280',
        '640x480',
        '480x800',
        '400x240',
        '320x240',
        '240x320'
    ];

    /**
     * 获取必应的壁纸
     * 国内版壁纸更新比国际版快一些
     * @param $idx : 今天为0，昨天为1，前天为2，以此类推
     * @param $num : 多少条记录
     * @return array
     */
    public function getLatestPic($idx = 0, $num = 1)
    {
        $url = 'https://cn.bing.com/HPImageArchive.aspx';
        $params = [
            'format' => 'js',
            'idx' => $idx,
            'n' => $num
        ];
        $result = Http::withHeaders([
            'cookie' => 'ENSEARCH=BENVER=0'
        ])->get($url, $params);
        $items = [];
        if (isset($result['images'])) {
            $items = $result['images'];
        }
        $params = [];
        foreach ($items as $item) {
            $param = [
                'startdate' => $item['startdate'],
                'fullstartdate' => $item['fullstartdate'],
                'enddate' => $item['enddate'],
                'url' => 'https://cn.bing.com' . $item['url'],
                'copyright' => $item['copyright'],
                'title' => $item['title'],
                'hsh' => $item['hsh'],
                'urlbase' => $item['urlbase'],
            ];
            $params []= $param;
        }
        return $params;
    }

    public function download($url)
    {
        $url = str_replace('1920x1080', 'UHD', $url);
        $arr = explode('?', $url)[1];
        $params = explode('&', $arr);
        $fileName = '';
        foreach ($params as $param) {
            $keyVal = explode('=', $param);
            if ($keyVal[0] == 'id') {
                $fileName = $keyVal[1];
                break;
            }
        }
        $path = '/public/bing/' . date('Y') .'/' . $fileName;
        // 下载最高分辨率的壁纸
        $rsp = Http::get($url);
        $i = 0;
        while ($rsp->status() == 404) {
            $url = str_replace($this->fileTypes[$i], $this->fileTypes[$i + 1], $url);
            $i += 1;
            $rsp = Http::get($url);
        }
        $path = str_replace('1920x1080', $this->fileTypes[$i], $path);
        debugger($path);
        Storage::put($path, $rsp);
        return $path;
    }
}
